from django.shortcuts import render

# Create your views here.


from django.http import JsonResponse
from django.views import View

from apps.areas.models import Area
from utils.response_code import RETCODE
from django.core.cache import cache


class AreasView(View):
    def get(self,request):
        parent_id = request.GET.get("area_id")
        if parent_id is None:
            # 先读取缓存
            cache_pro = cache.get("cache_pro")
            if cache_pro is None:
                # 没缓存


                proviences = Area.objects.filter(parent=None)
                # 对象列表转为字典
                # JsonResponse 默认对字典进行JSON转换
                cache_pro = []
                for pro in proviences:
                    cache_pro.append({
                        "id":pro.id,
                        "name":pro.name
                    })

                # 设置缓存"cache_pro",pro_list,24*3600  key,value,时长
                cache.set("cache_pro",cache_pro,24*3600)

            return JsonResponse({"code":RETCODE.OK,"province_list":cache_pro})

            # return JsonResponse(pro_list,safe=False)

        else:
            # 市/区县
            # parent_id
            # 先获取缓存
            city_list = cache.get("city_%s"%parent_id)
            # 判断
            if city_list is None:
            # 1.根据省的id查询市   查询集
            # pro = Area.objects.get(id=parent_id)
            # cities = pro.subs.all()
            # 另一种
                cities = Area.objects.filter(parent_id=parent_id)

                # 2.将对象遍历,转换为字典
                city_list = []
                for city in cities:
                    city_list.append({
                        "id":city.id,
                        "name":city.name
                    })

                # 存储到redis
                cache.set("city_%s"%parent_id,city_list,24*3600)
            # 3.返回响应
            return JsonResponse({"code":RETCODE.OK,"subs":city_list})
            # return JsonResponse(city_list,safe=False)






























